<?php

/**
 * @Author: wuchenge
 * @Date:   2022-04-19 13:56:17
 * @Email: ligui0506@126.com
 * @Descript:
 */
namespace App\Admin\Controllers;

use App\Http\Controllers\ApiController;
use App\Libraries\Qiniu;
use App\Models\Label;
use App\Requests\LabelRequest;
use Illuminate\Http\Request;

class LabelController extends ApiController
{
    protected $model;
    protected $request;
    public function __construct(Request $request)
    {
        $this->request = $request;
        $this->model   = new Label();
    }

    public function add(LabelRequest $request)
    {
        $title  = $request->input('title', '');
        $img    = $request->input('img', '');
        $status = $request->input('status', $this->model::STATUS_YES);

        $sort = $this->model::getMaxSort();

        $res = $this->model::create([
            'title'  => $title,
            'sort'   => $sort,
            'status' => $status,
            'img'    => $img,
        ]);

        if ($res) {
            return $this->response();
        }

        return $this->failed();
    }

    public function modify(LabelRequest $request)
    {
        $title  = $request->input('title', '');
        $id     = $request->input('id', 0);
        $img    = $request->input('img', '');
        $status = $request->input('status', $this->model::STATUS_YES);

        $model = $this->model::where('id', $id)->first();
        if (!$model) {
            return $this->failed();
        }
        // 更新
        $model->title  = $title;
        $model->img    = $img;
        $model->status = $status ? $this->model::STATUS_YES : $this->model::STATUS_NO;
        $res           = $model->save();

        if ($res) {
            return $this->response();
        }

        return $this->failed();
    }

    public function detail($id)
    {
        $res = $this->model::where('id', $id)->first();
        return $this->response($res);
    }

    public function del(Request $request)
    {
        $id  = $request->input('id', 0);
        $res = $this->model::del($id);
        if ($res['status']) {
            return $this->response();
        }
        return $this->failed();
    }

    public function lists(Request $request)
    {
        $title = $request->input('title', '');
        $model = $this->model::select(['*']);
        if (!empty($title)) {
            $model->where('title', 'like', '%' . $title . '%');
        }
        $data = $model->orderBy('sort', 'asc')->get()->toArray();
        return $this->response($data);
    }

    public function qiniu()
    {
        $result = Qiniu::getToken();
        if ($result['status']) {
            return $this->response($result['data']);
        }

        return $this->failed($result['message']);
    }
}
